package com.weather.androidweather.util;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolManager {
    private static ThreadPoolManager instance;
    private ThreadPoolExecutor executor;

    private ThreadPoolManager() {
        // 获取CPU核心数
        int cpuCount = Runtime.getRuntime().availableProcessors();
        // 核心线程数 = CPU核心数 + 1
        int corePoolSize = cpuCount + 1;
        // 最大线程数 = CPU核心数 * 2 + 1
        int maximumPoolSize = cpuCount * 2 + 1;
        // 线程空闲时间
        long keepAliveTime = 60L;
        
        executor = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    public static ThreadPoolManager getInstance() {
        if (instance == null) {
            synchronized (ThreadPoolManager.class) {
                if (instance == null) {
                    instance = new ThreadPoolManager();
                }
            }
        }
        return instance;
    }

    public void execute(Runnable task) {
        if (executor != null && !executor.isShutdown()) {
            executor.execute(task);
        }
    }

    public void shutdown() {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
        }
    }
} 